package com.thouiot.test.modbus.exception.handler;

import com.thouiot.common.exception.ErrorCodeEnum;
import com.thouiot.common.result.ResultUtil;
import com.thouiot.common.result.TiotResult;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @description Web请求全局错误处理
 * @author wangkai
 * @date 2025/04/17 09:10
 */
@RestController
public class ModbusErrHandlerController implements ErrorController {

    private final String ATTRIBUTE_NAME = "javax.servlet.error.status_code";

    /**
     * 错误处理，Spring默认error path 为 /error
     * @param request
     * @return
     */
    @RequestMapping("/error")
    @ResponseBody
    public TiotResult handleError(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        switch (status) {
            case UNAUTHORIZED:
                return ResultUtil.builderResult(ErrorCodeEnum.UNAUTHORIZED);
            case NOT_FOUND:
                return ResultUtil.builderResult(ErrorCodeEnum.NOT_FOUND);
            case INTERNAL_SERVER_ERROR:
            default:
                return ResultUtil.builderResult(ErrorCodeEnum.SERVER_ERROR);
        }
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute(ATTRIBUTE_NAME);
        if (null == statusCode) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        } else {
            try {
                return HttpStatus.valueOf(statusCode);
            } catch (Exception ex) {
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }
        }
     }
}
